// // The Vue build version to load with the `import` command
// // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
// 引入element UI
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App';
// 引入路由
import router from './router';
// 引入状态管理
import store from './vuex/store';

import axios from 'axios';
Vue.prototype.$axios = axios;

Vue.config.productionTip = false;

// 使用element UI
Vue.use(ElementUI);
// 过滤器
import * as custom from './utils/util'

Object.keys(custom).forEach(key => {
  Vue.filter(key, custom[key])
})

import VueKeyCloak from '@dsb-norge/vue-keycloak-js'
Vue.config.productionTip = false


Vue.use(VueKeyCloak, {
  init: {
    // Use 'login-required' to always require authentication
    // If using 'login-required', there is no need for the router guards in router.js
    onLoad: 'login-required',
    checkLoginIframe: false
  },
  config: {
    "realm": process.env.VUE_APP_AUTH_REALM,
    "url": process.env.VUE_APP_AUTH_URL,
    "clientId":process.env.VUE_APP_AUTH_CLIENTID
  },
  onReady: (keycloak) => {
    tokenInterceptor()
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      store, //使用store vuex状态管理
      components: {
        App
      },
      template: '<App/>',
      data: {
        // 空的实例放到根组件下，所有的子组件都能调用
        Bus: new Vue()
      }

    })

    setInterval(() => {
      keycloak.updateToken(70).then((refreshed) => {
        if (refreshed) {
          console.log('Token refreshed' + refreshed);
        } else {
          console.log('Token not refreshed, valid for '
            + Math.round(keycloak.tokenParsed.exp + keycloak.timeSkew - new Date().getTime() / 1000) + ' seconds');
        }
      }).catch(() => {
        console.log('Failed to refresh token');
      });
    }, 10000)

  }
})

function tokenInterceptor () {
  axios.interceptors.request.use(config => {
    if (Vue.prototype.$keycloak.authenticated) {
      config.headers.Authorization = `Bearer ${Vue.prototype.$keycloak.token}`
    }
    return config
  }, error => {
    return Promise.reject(error)
  })
}

